import axios from 'axios'
import { Message } from 'element-ui'

const request = axios.create({
  baseURL: 'http://localhost:24081/',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 打印请求信息，便于调试
    console.log('Request:', {
      url: config.url,
      method: config.method,
      data: config.data,
      params: config.params
    })
    return config
  },
  error => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 打印响应数据，便于调试
    console.log('Response:', response.data)
    
    const res = response.data
    if (res.code !== 200) {
      Message({
        message: res.msg || '错误',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || '错误'))
    }
    return res
  },
  error => {
    console.error('Response Error:', error.response || error)
    Message({
      message: error.response?.data?.msg || '请求失败',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default request 